package com.project.finance.shiro;




import com.project.finance.common.po.TbSysPermission;
import com.project.finance.common.po.TbSysUser;
import com.project.finance.role.service.PermissionService;
import com.project.finance.system.service.SystemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SystemService systemService;

    @Autowired
    private PermissionService permissionService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection princ) {
        String principal = (String) princ.getPrimaryPrincipal();
        //从数据库查询用户拥有的权限
        List<TbSysPermission> permByLoginName = permissionService.findPermByLoginName(principal);
        if (permByLoginName!=null){
            Set<String> stringPermissions = new HashSet<>();
            for (TbSysPermission perm : permByLoginName) {
                stringPermissions.add(perm.getPerName());
            }
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            //授权
            authorizationInfo.setStringPermissions(stringPermissions);
            return authorizationInfo;
        }
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户信息
        String loginname = (String) token.getPrincipal();
        log.info(loginname+"---------");
        TbSysUser sysUser = systemService.getSysUserByName(loginname);

        if (sysUser!=null){
            String password = sysUser.getPassword();
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(loginname, password, this.getName());
            return authenticationInfo;
        }


        return null;
    }
}
